#include <Windows.h>
#include <mmsystem.h>
#include <d3dx9.h>
#pragma warning( disable : 4996 ) // disable deprecated warning 
#include <strsafe.h>
#pragma warning( default : 4996 )

#define WIN_WIDTH 480
#define WIN_HEIGHT 272
#include "../../core/base/timer.h"
#include "../../app_frame/app_frame.h"
#include "XBoxController.h"

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
LPDIRECT3D9             g_pD3D = NULL; // Used to create the D3DDevice
LPDIRECT3DDEVICE9       g_pd3dDevice = NULL; // Our rendering device
D3DPRESENT_PARAMETERS	g_d3dpp;
unsigned int g_viewportWidth = 0;
unsigned int g_viewportHeight = 0;

bool g_isInMouseDraging = false;  // Indicate whether the user push the LMB down and keep mouse moving
CXBOXController g_xbController(1);

// Main entry points of the App
bool InitApp();
void DestoryApp();
bool TimeElapse(double sec);


char g_internalDebugString[512] = {"Windows platform..."};
const char* __getDebugStatusString()
{
	return g_internalDebugString;
}

void SetDefaultRS()
{
	if (!g_pd3dDevice)
		return;
	g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
	g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
	g_pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE );

	g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
	g_pd3dDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
	g_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
	g_pd3dDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);

}

HRESULT InitD3D( HWND hWnd )
{
	// Create the D3D object.
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return E_FAIL;

	ZeroMemory( &g_d3dpp, sizeof( g_d3dpp ) );
	g_d3dpp.Windowed = TRUE;
	g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	g_d3dpp.EnableAutoDepthStencil = FALSE;
	g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

	// Create the D3DDevice
	if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&g_d3dpp, &g_pd3dDevice ) ) )
	{
		return E_FAIL;
	}
	SetDefaultRS();
	
	return S_OK;
}


VOID Cleanup()
{
	if( g_pd3dDevice != NULL )
		g_pd3dDevice->Release();

	if( g_pD3D != NULL )
		g_pD3D->Release();

	g_pd3dDevice = NULL;
	g_pD3D = NULL;
}


//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	switch( msg )
	{
	case WM_CREATE:
		{
			RECT clientRect, winRect;
			GetClientRect(hWnd, &clientRect);
			GetWindowRect(hWnd, &winRect);
			LONG extraWidth = winRect.right - winRect.left - clientRect.right + clientRect.left;
			LONG extraHeight = winRect.bottom - winRect.top - clientRect.bottom + clientRect.top;

			MoveWindow(hWnd, winRect.left, winRect.top, WIN_WIDTH + extraWidth, WIN_HEIGHT + extraHeight, TRUE);
		}
		break;
	case WM_SIZE:
		{
			RECT clientRect;
			GetClientRect(hWnd, &clientRect);
			g_d3dpp.BackBufferWidth = clientRect.right - clientRect.left;
			g_d3dpp.BackBufferHeight = clientRect.bottom - clientRect.top;
			if (g_pd3dDevice) {
				g_pd3dDevice->Reset(&g_d3dpp);
				SetDefaultRS();
			}
			g_viewportWidth = clientRect.right - clientRect.left;
			g_viewportHeight = clientRect.bottom - clientRect.top;
		}
		break;
	case WM_LBUTTONDOWN: {
			SetCapture(hWnd);
			g_isInMouseDraging = true;
			KVec2 pos;
			pos[0] = float(LOWORD(lParam));
			pos[1] = float(g_viewportHeight - (int)HIWORD(lParam));
			KAppFrame::GetInstance()->mTouchEvents.PushEvent(KTouchEvent::eTouchDown, pos);
		}
		break;
	case WM_LBUTTONUP: {
			g_isInMouseDraging = false;
			ReleaseCapture();
			KVec2 pos;
			pos[0] = float(LOWORD(lParam));
			pos[1] = float(g_viewportHeight - (int)HIWORD(lParam));
			KAppFrame::GetInstance()->mTouchEvents.PushEvent(KTouchEvent::eTouchUp, pos);
		}
		break;
	case WM_MOUSEMOVE: {
			if (g_isInMouseDraging) {
				KVec2 pos;
				pos[0] = float(LOWORD(lParam));
				pos[1] = float(g_viewportHeight - (int)HIWORD(lParam));
				KAppFrame::GetInstance()->mTouchEvents.PushEvent(KTouchEvent::eTouchMove, pos);
			}
		}
		break;
	case WM_DESTROY:
		DestoryApp();

		Cleanup();
		PostQuitMessage( 0 );
		return 0;
	}

	return DefWindowProc( hWnd, msg, wParam, lParam );
}




//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
	UNREFERENCED_PARAMETER( hInst );
	const char* winClassName = "KNyetWinClass";
	// Register the window class
	WNDCLASSEX wc =
	{
		sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L,
		GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
		winClassName, NULL
	};
	RegisterClassEx( &wc );

	// Create the application's window
	HWND hWnd = CreateWindow( winClassName, "KNyetApp",
		WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, WIN_WIDTH, WIN_HEIGHT,
		NULL, NULL, wc.hInstance, NULL );

	// Initialize Direct3D
	if( SUCCEEDED( InitD3D( hWnd ) ) )
	{
		// Create the scene geometry
		if( InitApp())
		{
			// Show the window
			ShowWindow( hWnd, SW_SHOWDEFAULT );
			UpdateWindow( hWnd );

			// Enter the message loop
			MSG msg;
			ZeroMemory( &msg, sizeof( msg ) );
			KTimer timer(true);
			while( msg.message != WM_QUIT )
			{
				if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
				{
					TranslateMessage( &msg );
					DispatchMessage( &msg );
				}
				else{

					
					bool needRender = true;
					if (g_pd3dDevice) {
						HRESULT hr = g_pd3dDevice->TestCooperativeLevel();
						if (D3DERR_DEVICENOTRESET == hr) {
							g_pd3dDevice->Reset(&g_d3dpp);
							SetDefaultRS();
						}
						else if (D3DERR_DEVICELOST == hr) {
							needRender = false;
						}
					}

					if (needRender) {

						g_xbController.Convert(KAppFrame::GetInstance()->mGamePadStatus);
						if (!TimeElapse(timer.Stop()))
							PostQuitMessage(0);
						else {
							KAppFrame::GetInstance()->mTouchEvents.Reset();
							// Present the back buffer contents to the display
							g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
						}

					}
				}
			}
		}
	}

	UnregisterClass( winClassName, wc.hInstance );
	return 0;
}
